// static/script.js
document.addEventListener('DOMContentLoaded', function() {
    const track = document.getElementById('carouselTrack');
    const indicatorsContainer = document.getElementById('indicators');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');

    let currentIndex = 0;
    let images = [];
    let slideCount = 0;
    let autoPlay;
    let isModalOpen = false;
    let currentModalIndex = 0;

    // 从服务器获取图片列表
    fetch('/api/images')
        .then(response => response.json())
        .then(data => {
            images = data;
            slideCount = images.length;
            initCarousel();
            startAutoPlay();
        })
        .catch(error => {
            console.error('Error loading images:', error);
            // 使用默认图片
            images = [
                {filename: 'sample1.jpg', title: '星空下的约定', description: '与你一起仰望星空的夜晚'},
                {filename: 'sample2.jpg', title: '海边漫步', description: '海风轻抚，与你同行'},
                {filename: 'sample3.jpg', title: '花海徜徉', description: '在花海中寻找你的身影'}
            ];
            slideCount = images.length;
            initCarousel();
            startAutoPlay();
        });

    // 初始化轮播
    function initCarousel() {
        // 创建轮播项
        track.innerHTML = '';
        images.forEach((image, index) => {
            const slide = document.createElement('div');
            slide.className = 'carousel-slide';

            slide.innerHTML = `
                <div class="image-container" data-index="${index}">
                    <img src="/photos/${encodeURIComponent(image.filename)}" alt="${image.title}">
                    <div class="overlay">
                        <div class="text-content">
                            <h2>${image.title}</h2>
                            <p>${image.description}</p>
                        </div>
                    </div>
                </div>
            `;

            track.appendChild(slide);
        });

        // 创建指示器
        indicatorsContainer.innerHTML = '';
        images.forEach((_, index) => {
            const indicator = document.createElement('span');
            indicator.className = 'indicator';
            if (index === 0) indicator.classList.add('active');
            indicator.dataset.index = index;
            indicator.addEventListener('click', () => goToSlide(index));
            indicatorsContainer.appendChild(indicator);
        });

        // 为图片容器添加点击事件
        setTimeout(() => {
            const imageContainers = document.querySelectorAll('.image-container');
            imageContainers.forEach(container => {
                container.addEventListener('click', handleImageClick);
            });
        }, 100);

        updateCarousel();
    }

    // 图片点击事件处理
    function handleImageClick(e) {
        const container = e.currentTarget;
        const index = parseInt(container.dataset.index);
        openModal(index);
    }

    // 打开放大模式
    function openModal(index) {
        if (isModalOpen) return;

        isModalOpen = true;
        currentModalIndex = index;
        clearInterval(autoPlay);

        // 创建模态框
        const modalOverlay = document.createElement('div');
        modalOverlay.className = 'modal-overlay';

        modalOverlay.innerHTML = `
            <div class="modal-content">
                <img src="/photos/${encodeURIComponent(images[currentModalIndex].filename)}" alt="${images[currentModalIndex].title}">
                <button class="modal-nav modal-prev">&#10094;</button>
                <button class="modal-nav modal-next">&#10095;</button>
                <button class="modal-close">&times;</button>
                <div class="modal-title">
                    <h3>${images[currentModalIndex].title}</h3>
                    <p>${images[currentModalIndex].description}</p>
                </div>
            </div>
        `;

        document.body.appendChild(modalOverlay);

        // 绑定事件
        const modalPrev = modalOverlay.querySelector('.modal-prev');
        const modalNext = modalOverlay.querySelector('.modal-next');
        const modalClose = modalOverlay.querySelector('.modal-close');
        const modalImg = modalOverlay.querySelector('img');

        modalPrev.addEventListener('click', (e) => {
            e.stopPropagation();
            prevModalImage();
        });

        modalNext.addEventListener('click', (e) => {
            e.stopPropagation();
            nextModalImage();
        });

        modalClose.addEventListener('click', closeModal);

        modalOverlay.addEventListener('click', (e) => {
            if (e.target === modalOverlay) {
                closeModal();
            }
        });

        // 键盘事件
        document.addEventListener('keydown', handleModalKeydown);
    }

    // 关闭放大模式
    function closeModal() {
        const modalOverlay = document.querySelector('.modal-overlay');
        if (modalOverlay) {
            document.body.removeChild(modalOverlay);
        }
        isModalOpen = false;
        document.removeEventListener('keydown', handleModalKeydown);
        startAutoPlay();
    }

    // 放大模式下切换到下一张图片
    function nextModalImage() {
        currentModalIndex = (currentModalIndex + 1) % images.length;
        updateModalImage();
    }

    // 放大模式下切换到上一张图片
    function prevModalImage() {
        currentModalIndex = (currentModalIndex - 1 + images.length) % images.length;
        updateModalImage();
    }

    // 更新放大模式下的图片
    function updateModalImage() {
        const modalImg = document.querySelector('.modal-content img');
        const modalTitle = document.querySelector('.modal-title');

        if (modalImg && modalTitle) {
            modalImg.src = `/photos/${encodeURIComponent(images[currentModalIndex].filename)}`;
            modalImg.alt = images[currentModalIndex].title;
            modalTitle.innerHTML = `
                <h3>${images[currentModalIndex].title}</h3>
                <p>${images[currentModalIndex].description}</p>
            `;
        }
    }

    // 放大模式下的键盘事件处理
    function handleModalKeydown(e) {
        if (!isModalOpen) return;

        switch (e.key) {
            case 'ArrowLeft':
                prevModalImage();
                break;
            case 'ArrowRight':
                nextModalImage();
                break;
            case 'Escape':
                closeModal();
                break;
        }
    }

    // 更新轮播位置
    function updateCarousel() {
        if (track) {
            track.style.transform = `translateX(-${currentIndex * 100}%)`;
        }

        // 更新指示器
        const indicators = document.querySelectorAll('.indicator');
        indicators.forEach((indicator, index) => {
            if (index === currentIndex) {
                indicator.classList.add('active');
            } else {
                indicator.classList.remove('active');
            }
        });
    }

    // 跳转到指定幻灯片
    function goToSlide(index) {
        currentIndex = index;
        updateCarousel();
    }

    // 下一张
    function nextSlide() {
        currentIndex = (currentIndex + 1) % slideCount;
        updateCarousel();
    }

    // 上一张
    function prevSlide() {
        currentIndex = (currentIndex - 1 + slideCount) % slideCount;
        updateCarousel();
    }

    // 自动轮播
    function startAutoPlay() {
        clearInterval(autoPlay);
        autoPlay = setInterval(nextSlide, 4000);
    }

    // 鼠标悬停时暂停自动播放
    const carouselContainer = document.querySelector('.carousel-container');
    if (carouselContainer) {
        carouselContainer.addEventListener('mouseenter', () => {
            clearInterval(autoPlay);
        });

        carouselContainer.addEventListener('mouseleave', () => {
            startAutoPlay();
        });
    }

    // 绑定按钮事件
    if (nextBtn) nextBtn.addEventListener('click', nextSlide);
    if (prevBtn) prevBtn.addEventListener('click', prevSlide);

    // 键盘导航（正常模式下）
    document.addEventListener('keydown', (e) => {
        if (isModalOpen) return;

        if (e.key === 'ArrowLeft') {
            prevSlide();
        } else if (e.key === 'ArrowRight') {
            nextSlide();
        }
    });

    // 触摸滑动支持
    let startX = 0;
    let endX = 0;

    if (carouselContainer) {
        carouselContainer.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
        });

        carouselContainer.addEventListener('touchend', (e) => {
            endX = e.changedTouches[0].clientX;
            handleSwipe();
        });
    }

    function handleSwipe() {
        if (isModalOpen) return;

        const swipeThreshold = 50;
        const diff = startX - endX;

        if (Math.abs(diff) > swipeThreshold) {
            if (diff > 0) {
                nextSlide(); // 向左滑动，显示下一张
            } else {
                prevSlide(); // 向右滑动，显示上一张
            }
        }
    }
});